package cn.felord.oss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import org.springframework.util.Assert;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * @author felord.cn
 * @since 2020/8/24 20:17
 */
public class AliyunStorage implements Storage {

    private final Map<String, OSSClient> ossClientMap;

    public AliyunStorage(Map<String, OSSClient> ossClientMap) {
        this.ossClientMap = ossClientMap;
    }

    @Override
    public void putObject(String bucketName, String objectName, InputStream inputStream, String contentType) {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(contentType);
        OSSClient ossClient = ossClientMap.get(bucketName);
        Assert.notNull(ossClient, "oss bucket " + bucketName + " not found");
        ossClient.putObject(bucketName, objectName, inputStream, objectMetadata);
    }

    @Override
    public InputStream getObject(String bucketName, String objectName) {
        OSSClient ossClient = ossClientMap.get(bucketName);
        Assert.notNull(ossClient, "oss bucket " + bucketName + " not found");
        return ossClient.getObject(bucketName, objectName).getObjectContent();
    }

    @Override
    public String getObjectUrl(String bucketName, String objectName) {
        OSSClient ossClient = ossClientMap.get(bucketName);
        Assert.notNull(ossClient, "oss bucket " + bucketName + " not found");
        return "https://" + bucketName + "." + ossClient.getEndpoint().getHost() + "/" + objectName;
    }

    @Override
    public void removeObject(String bucketName, String objectName) throws Exception {
        OSSClient ossClient = ossClientMap.get(bucketName);
        Assert.notNull(ossClient, "oss bucket " + bucketName + " not found");
        ossClient.deleteObject(bucketName, objectName);
    }
}
